
import System.Console;
import System.ConsoleColor;
import System.IO.Path;
import System.Xml.XmlDocument;
import System.Xml.XmlNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.silverfoxserver.core.log.Log;
import net.silverfoxserver.core.socket.SocketAcceptor;
import net.silverfoxserver.core.socket.SocketConnector;
import net.silverfoxserver.core.util.SR;
import net.silverfoxserver.ext.Globals;
import net.silverfoxserver.ext.handler.GameClientHandler;
import net.silverfoxserver.ext.handler.GameServerHandler;
import org.jdom2.Element;
import org.jdom2.JDOMException;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ACER-FX
 */
public class Program {
    
    //定义游戏名称,显示在控制台上
    public static String GAME_NAME;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        //os            
        String os = System.getProperty("os.name");
            
        Globals.os = os;
        
        //lang
        Locale machine = Locale.getDefault();
        String lang = machine.getLanguage() + "-" + machine.getCountry();//"zh-CN"; // System.Globalization.CultureInfo.InstalledUICulture.Name;

        Globals.lang = lang;
        
        SR.init(lang);
        
        //log
        Log.init("FlashGate",0);    
        
        //
        
        //stage.setTitle("Flash Gate Service (build date:2016/8/9)");               
        
        //
        loadXMLConfigAndStart();        
        
    }
    
    //public void loadXMLConfig()
    public static void loadXMLConfigAndStart()
    {
        
        try {
    //load xml config
        //读取xml配置
        XmlDocument configDoc = new XmlDocument();

        //获取和设置当前目录（即该进程从中启动的目录）的完全限定路径。
        //string str = System.Environment.CurrentDirectory;
        //该程序如果由另一程序启动，则会有问题，获得的是另一程序的启动路径

        //
        String configFileName = "FlashGateCloudServerConfig.xml";

        //
        String ApplicationBase = "";//System.getProperty("user.dir");

        if(Globals.os.equals("Linux"))
        {
            //在Linux下面用这个方法,获得执行jar的运行路径
            String javaClassPath = System.getProperty("java.class.path");
            ApplicationBase = javaClassPath.substring(0,
                    javaClassPath.lastIndexOf("/")
                    );

        }else{

            ApplicationBase = System.getProperty("user.dir");
        }

        //            
        String configFileFullPath = Path.Combine(ApplicationBase, configFileName);

        //
        //Console.WriteLine("[Load File] " + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + configFileName);

        Globals.out.println(SR.GetString(SR.getLoadFile(), configFileFullPath));
        
        
        configDoc.Load(configFileFullPath);
        


        //IP信息
        XmlNode node = configDoc.SelectSingleNode("/SilverFoxConfig/group/main-server");

        if (null == node)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Globals.out.println(SR.GetString(SR.getCan_not_find_node(),"/SilverFoxConfig/group/main-server"));
            Console.ForegroundColor = ConsoleColor.Green;
        }
                
        
        //
        String n = node.ChildNodes()[0].getText();
        Program.GAME_NAME = n;
        
           
        
        
        String ipAdr = node.ChildNodes()[1].getText();

        int port = Integer.parseInt(node.ChildNodes()[2].getText());        
                
        
        //
        XmlNode connectServersNode = configDoc.SelectSingleNode("/SilverFoxConfig/group/connect-servers");//game-server
        
        int connectServersCount = connectServersNode.ChildNodes().length;
        
        //ArrayList<SocketConnector> connectServerList = new ArrayList<SocketConnector>() {};
        
        ConcurrentHashMap connectServerList = Globals.mainWindowModel.getConnectServerList();
        
        for(int i=0;i<connectServersCount;i++)
        {
            
            Element gameServerNode = connectServersNode.ChildNodes()[i];
            
            String connectName = gameServerNode.getChildText("n");    
            
            String connectIp = gameServerNode.getChildText("ip");             
            
            int connectPort = Integer.parseInt(gameServerNode.getChildText("port"));
            String connectProof = gameServerNode.getChildText("proof");
            
            SocketConnector connector = new SocketConnector(connectProof,connectName);
            connector.setHandler(new GameServerHandler(connectName));
            
            connectServerList.put(connectName,connector);
            
            connector.connect(connectIp, connectPort);
        }
        
               
        
        //------------------------------------------------------
        Globals.out.println(SR.GetString(SR.getLoadFileSuccess()));
        
        
        
        
        Globals.mainWindowModel.acceptor = new SocketAcceptor(GAME_NAME);
        
        SocketAcceptor acceptor = Globals.mainWindowModel.acceptor;
        
        acceptor.setHandler(new GameClientHandler(),true);
        
        //最后启动外网侦听
        acceptor.bind(port, false);
        
        
        
        } catch (JDOMException | IOException ex) {
            
            
            Globals.out.println(ex.getMessage());
            
        } 
    
    
    }
    
}
